//
//  ChatListVC.m
//  ChangChat
//
//  Created by Cocoa on 2019/8/20.
//  Copyright © 2019 yibai. All rights reserved.
//

#import "ChatListVC.h"
#import "TextMsgCell.h"
#import "ImageMsgCell.h"
#import "VideoMsgCell.h"
#import "CardMsgCell.h"
#import "FileMsgCell.h"
#import "VoiceMsgCell.h"
#import "TimeMsgCell.h"
#import "AudioPlayerHelper.h"
#import "CRPreview.h"
#import "YBVideoPlayerVC.h"
#import <LKDBHelper/LKDBHelper.h>
#import "FriendInfoListVC.h"
#import "MineListVC.h"
#import "YBFileShowVC.h"
#import "AddressListVC.h"
#import "SendCardAlert.h"
#import "YBApiManager+Chat.h"
#import "NSDate+Debug.h"
#import "YCMenuView.h"
#import "CacheHelper.h"
#import "EVCPopInputView.h"
#import "YBApiManager+Friend.h"
#import "BaseNavigationController.h"
#import "AXWebViewController.h"
#import "GroupDetailVC.h"

@interface ChatListVC ()<IMManagerDelegate>
@property (nonatomic, strong) NSIndexPath *lastPlayVoiceMsgIndexPath;
@property (nonatomic, strong) NSIndexPath *longPressIndexPath;
@property (nonatomic, assign) CGFloat lastTableViewHeight;
@property (nonatomic, strong) UIBarButtonItem *rightBarBtnItem;
@end

@implementation ChatListVC
- (void)dealloc {
    
    kUsermanager.currentSession = nil;
}
- (void)setSession:(SessionItem *)session {
    _session = session;
    kUsermanager.currentSession = session;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self setupDatasource];
    [self setUnReceivedMsgToReceived];
    @weakify(self);
    [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:notification_Friend_Info_Changed object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        FriendItem *item = x.object;
        if ([item.group_id isEqualToString:self.session.group_id] == YES || self.session.isGroupChat == YES) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
    }];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (self.lastPlayVoiceMsgIndexPath) {
        MsgModel *model = self.dataSource[self.lastPlayVoiceMsgIndexPath.row];
        if (model.playing == YES) {
            [self playVoiceWithIndexPath:self.lastPlayVoiceMsgIndexPath];
        }
    }
}
- (void)setupUI {
    
    NSArray *cells = @[@"TextMsgCell",@"ImageMsgCell",@"VideoMsgCell",@"CardMsgCell",@"FileMsgCell",@"VoiceMsgCell",@"TimeMsgCell", @"TipMsgCell"];
    
//    [self.dataSource addObjectsFromArray:cells];
    for (NSString *cellId in cells) {
        [self.tableView customRegisterClassWithName:cellId];
    }
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.parentViewController.navigationItem.rightBarButtonItem = self.rightBarBtnItem;
    
}
- (UIBarButtonItem *)rightBarBtnItem {
    if (_rightBarBtnItem == nil) {
        UIButton *btn = UIButton.k_init().k_img(UIImage.k_imgName(@"global_more")).k_font([UIFont boldSystemFontOfSize:15]);
        btn.tintColor = UIColor.whiteColor;
        
        _rightBarBtnItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
        @weakify(self);
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            
            if (self.session.isGroupChat == YES || self.session.isSingleFriendChat == NO) {
                GroupDetailVC *groupDetailVC = [GroupDetailVC new];
                groupDetailVC.group = [GroupItem searchSingleWithWhere:@{@"group_id": self.session.group_id} orderBy:nil];
                [groupDetailVC setDidCleanGroupMsgBlock:^{
                    [self.dataSource removeAllObjects];
                    [self.tableView reloadData];
                }];
                [self.navigationController pushViewController:groupDetailVC animated:YES];
                return;
            }
            
            NSArray *titles = @[@"清空聊天", @"举报用户"];
            
            [LBXAlertAction showActionSheetWithTitle:@"更多" message:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitle:titles chooseBlock:^(NSInteger buttonIdx) {
                if (buttonIdx == 1) {
                    [self didClickRightBarBtnItemAction];
                } else if (buttonIdx == 2) {
                    [self didClickReportUser];
                }
            }];
        }];
    }
    return _rightBarBtnItem;
}
- (void)setupDatasource {
    [[IMManager shareManager] addIMDelegate:self];

    NSArray *arrs = [[MsgItem searchWithWhere:@{@"group_id": self.session.group_id?:@"-100"} orderBy:@"createtime asc" offset:0 count:0].rac_sequence map:^id _Nullable(id  _Nullable value) {
        MsgModel *model = MsgModel.new;
        model.msg = value;
        return model;
    }].array;
    [self.dataSource addObjectsFromArray:arrs];
    
    [self.tableView reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{    
        [self scrollToBottom];
    });
}
#pragma mark - 消息置为已收到
- (void)setUnReceivedMsgToReceived {
    for (MsgModel *model in self.dataSource) {
        //  本地消息置为已收到
        model.msg.is_received = YES;
        //  消息置为已读
        if (model.msg.is_read == NO) {
            model.msg.is_read = YES;
            [model.msg updateToDB];
        }
    }
    //  服务端消息置为已读
    [self setMsgIsRead];
}
- (void)setMsgIsRead {
    if (self.session) {
        self.session.unread_msg_count = 0;
        [self.session updateToDB];
        [[YBApiManager.shareManager sendReadedMsgWithGroupId:self.session.group_id] subscribeNext:^(id  _Nullable x) {
        }];
    }
}

#pragma mark - msg + delegate
- (void)addNewMessage:(MsgModel *)msgModel {
    [self.dataSource addObject:msgModel];
    [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.dataSource.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self scrollToBottom];
}
- (void)imManager:(IMManager *)manager receiveMsg:(MsgModel *)msgModel {
    if ([msgModel.msg.group_id isEqualToString:self.session.group_id] == YES) {
        [self addNewMessage:msgModel];
        if ([msgModel.msg.send_user_id isEqualToString:kUsermanager.me.ID] == NO) {
            [self setMsgIsRead];
            msgModel.msg.is_read = YES;
            [msgModel.msg updateToDB];
        }
    }
}
- (void)imManager:(IMManager *)manager receiveFriendStatusMsg:(MsgItem *)msg {
    if (msg.type == MsgType_Friend_delete && [msg.group_id isEqualToString:self.session.group_id] == YES) {
        [MBProgressHUD showTipMessageInWindow:@"您已被对方删除好友。"];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
- (void)imManager:(IMManager *)manager recallMsg:(MsgItem *)msg {
    for (MsgModel *model in self.dataSource) {
        if (model.msg.message_id == msg.message_id || model.msg.remote_msg_id == msg.message_id) {
            model.msg = msg;
            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:[self.dataSource indexOfObject:model] inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
            return;
            break;
        }
    }
    MsgModel *model = MsgModel.new;
    model.msg = msg;
    [self addNewMessage:model];
}
- (void)imManager:(IMManager *)manager sendMsgSuccess:(MsgModel *)msgModel {
    if ([self.dataSource containsObject:msgModel] == NO) {
        [self.dataSource enumerateObjectsUsingBlock:^(MsgModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.msg.message_id == msgModel.msg.message_id) {
                
                obj.msg = msgModel.msg;
                NSIndexPath *targetIP = [NSIndexPath indexPathForRow:idx inSection:0];
                [self.tableView reloadRowsAtIndexPaths:@[targetIP] withRowAnimation:UITableViewRowAnimationNone];
                *stop = YES;
            }
        }];
    }
}
- (void)imManager:(IMManager *)manager sendMsgFailed:(MsgModel *)msgModel {
    if ([self.dataSource containsObject:msgModel] == NO) {
        [self.dataSource enumerateObjectsUsingBlock:^(MsgModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.msg.message_id == msgModel.msg.message_id) {
                obj.msg = msgModel.msg;
                NSIndexPath *targetIP = [NSIndexPath indexPathForRow:idx inSection:0];
                [self.tableView reloadRowsAtIndexPaths:@[targetIP] withRowAnimation:UITableViewRowAnimationNone];
                *stop = YES;
            }
        }];
    }
}

#pragma mark - tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MsgModel *msgModel = self.dataSource[indexPath.row];
    MessageBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:msgModel.msg.cellID forIndexPath:indexPath];
//    cell.msgTextLabel.text = @"圣诞节";
//    cell.msgTextLabel.text = arc4random()%2 == 0 ? @"圣诞节" : @"圣诞节开发就卡机的反馈盛开的积分开始的缴费卡圣诞节疯狂电视剧看风景的开始";
    
//    cell.msgDirection = arc4random() % 2 + 1;
    cell.msgModel = self.dataSource[indexPath.row];
    
    @weakify(self);
    if ([cell isKindOfClass:ImageMsgCell.class] == YES ||
        [cell isKindOfClass:VideoMsgCell.class] == YES ) {
        ImageMsgCell *msgCell = (ImageMsgCell *)cell;
        msgCell.imgLoaded = ^(UITableViewCell * _Nonnull cell) {
            @strongify(self);
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        };
    } else if (msgModel.msg.type == MsgType_Text) {
        TextMsgCell *textCell = (TextMsgCell *)cell;
        [textCell setDidTapLinkBlock:^(NSString * _Nonnull link) {
           @strongify(self);
            [self didClickLinkWithUrlStr:link];
        }];
    }
    
    
    [cell setTapIconAction:^(BOOL is_me) {
        @strongify(self);
        [self didClickIconActionWithIndexPath:indexPath isMe:is_me];
    }];
    [cell setTapMessageAction:^{
        @strongify(self);
        [self didClickMseeageContentActionWithIndexPath:indexPath];
    }];
    [cell setLongPressMessageAction:^{
        @strongify(self);
        [self didLongPressMessageContentActionWithIndexPath:indexPath];
    }];
    [[[cell.sendFailedBtn rac_signalForControlEvents:UIControlEventTouchUpInside] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        [self didClickResendMsgWithIndexPath:indexPath];
    }];
    return cell;
}

#pragma mark - msg action
- (void)didClickIconActionWithIndexPath:(NSIndexPath *)indexPath isMe:(BOOL)is_me {
    
//    if (is_me == YES) {
//        MineListVC *mineVC = MineListVC.new;
//        [self.navigationController pushViewController:mineVC animated:YES];
//        return;
//    }
    
    MsgModel *model = self.dataSource[indexPath.row];

    FriendInfoListVC *friendInfoVC = FriendInfoListVC.new;
    friendInfoVC.from = @"3";
    friendInfoVC.listType = 2;
    if (is_me == YES) {
        friendInfoVC.user = [FriendItem mj_objectWithKeyValues:kUsermanager.me];
    } else {
        friendInfoVC.user = [FriendItem new];
        friendInfoVC.user.friend_id = model.msg.send_user_id;
    }
    [self.navigationController pushViewController:friendInfoVC animated:YES];
}
- (void)didClickMseeageContentActionWithIndexPath:(NSIndexPath *)indexPath {
    MsgModel *model = self.dataSource[indexPath.row];
    
    if (model.msg.type == MsgType_Voice) {
        [self playVoiceWithIndexPath:indexPath];
    } else if (model.msg.type == MsgType_Photo) {
        [self lookPhotoWithIndexPath:indexPath];
    } else if (model.msg.type == MsgType_Video) {
        [self playVideoWithIndexPath:indexPath];
    } else if (model.msg.type == MsgType_Card) {
        [self lookCardInfoWithIndexPath:indexPath];
    } else if (model.msg.type == MsgType_File) {
        [self lookFileInfoWithIndexPath:indexPath];
    }
}
- (void)didLongPressMessageContentActionWithIndexPath:(NSIndexPath *)indexPath {
    MsgModel *model = self.dataSource[indexPath.row];
    if (model.msg.type == MsgType_Tip || model.msg.type == MsgType_Time) {
        return;
    }
    self.longPressIndexPath = indexPath;
    [self becomeFirstResponder];
    MessageBaseCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    UIMenuController *menu = [UIMenuController sharedMenuController];
    NSMutableArray *items = [NSMutableArray array];
    if (model.msg.type == MsgType_Text) {
        UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(didClickCopyMenuItem)];
        [items addObject:copyItem];
    }
//    if (model.msg.type != MsgType_Voice) {
        UIMenuItem *forwarding = [[UIMenuItem alloc] initWithTitle:@"转发" action:@selector(didClicForwardingMenuItem)];
        [items addObject:forwarding];
//    }
    
    UIMenuItem *deleteItem = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(didClickDeleteMenuItem)];
    [items addObject:deleteItem];
    
    if (((model.msg.message_id < 0 && model.msg.remote_msg_id > 0) ||
         (model.direction == MsgDirection_send && model.msg.message_id > 0)
         )
        && [NSDate isExceed2MinuteWithTargetTimestamp: model.msg.createtime] == NO)
    {
        UIMenuItem *deleteItem = [[UIMenuItem alloc] initWithTitle:@"撤回" action:@selector(didClickRecallMsg)];
        [items addObject:deleteItem];
    }
    
    
    menu.menuItems = items;
    [menu setTargetRect:cell.msgContentView.bounds inView:cell.msgContentView];
    [menu setMenuVisible:YES animated:YES];
}


- (void)didClickResendMsgWithIndexPath:(NSIndexPath *)indexPath {
    MsgModel *model = self.dataSource[indexPath.row];
    [[IMManager shareManager] resendMsg:model];
}

- (void)playVoiceWithIndexPath:(NSIndexPath *)indexPath {
    MsgModel *msg = self.dataSource[indexPath.row];
    msg.msg.is_received = YES;
    if (self.lastPlayVoiceMsgIndexPath && self.lastPlayVoiceMsgIndexPath != indexPath) {
        MsgModel *lastMsg = self.dataSource[self.lastPlayVoiceMsgIndexPath.row];
        if (lastMsg.playing == YES) {
            lastMsg.playing = NO;
            [self.tableView reloadRowsAtIndexPaths:@[self.lastPlayVoiceMsgIndexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
    if (msg.playing == YES) {
        msg.playing = NO;
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        [[AudioPlayerHelper helper] stopAudioPlay];
        return;
    }
    msg.playing = YES;
    self.lastPlayVoiceMsgIndexPath = indexPath;
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    MsgItem *voiceMsg = msg.msg;
    @weakify(self);
    [[AudioPlayerHelper helper] playAudioWithPath:voiceMsg.allFilePath finished:^(NSString * _Nonnull path) {
        msg.playing = NO;
        @strongify(self);
        NSArray *cells = [self.tableView visibleCells];
        for (MessageBaseCell *cell in cells) {
            if (cell.msgModel == msg) {
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                break;
            }
        }
    }];
}

- (void)lookPhotoWithIndexPath:(NSIndexPath *)indexPath {
//    MsgModel *msg = self.dataSource[indexPath.row];
    ImageMsgCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    CRPreview *preview = [[CRPreview alloc] initWithImage:cell.photoImgView.image];
    [preview show];
}
- (void)playVideoWithIndexPath:(NSIndexPath *)indexPath {
    MsgModel *msg = self.dataSource[indexPath.row];
    if ([NSDate isExceed30DayWithTagetTimestamp:msg.msg.createtime] == YES) {
        if (msg.msg.filePath == nil) {
            [MBProgressHUD showTipMessageInView:@"当前视频已过期，不可查看" timer:1.0f];
            return;
        }
    }
    YBVideoPlayerVC *playerVC = [[YBVideoPlayerVC alloc] init];
    playerVC.msg = msg.msg;
    [self presentViewController:playerVC animated:YES completion:nil];
    
}
- (void)lookCardInfoWithIndexPath:(NSIndexPath *)indexPath {
    
    MsgModel *msg = self.dataSource[indexPath.row];
    
    FriendInfoListVC *friendInfoVc = [FriendInfoListVC new];
    friendInfoVc.listType = 2;
    friendInfoVc.from = @"2";
    friendInfoVc.user = [FriendItem mj_objectWithKeyValues:msg.msg.content];
    [self.navigationController pushViewController:friendInfoVc animated:YES];
}
- (void)lookFileInfoWithIndexPath:(NSIndexPath *)indexPath {
    MsgModel *msg = self.dataSource[indexPath.row];
    
    if ([NSDate isExceed30DayWithTagetTimestamp:msg.msg.createtime] == YES) {
        
        if (msg.msg.filePath == nil) {
            [MBProgressHUD showTipMessageInView:@"当前文件已过期，不可查看" timer:1.0f];
            return;
        }
    }
    
    YBFileShowVC *fileVC = [YBFileShowVC new];
    fileVC.msgModel = msg;
    [self.navigationController pushViewController:fileVC animated:YES];
}
- (void)didClickCopyMenuItem {
    MsgModel *originMsg = self.dataSource[self.longPressIndexPath.row];
    UIPasteboard *pb = [UIPasteboard generalPasteboard];
    [pb setString:originMsg.msg.content];
}
- (void)didClicForwardingMenuItem {
    
    MsgModel *originMsg = self.dataSource[self.longPressIndexPath.row];
    MsgModel *msg = MsgModel.new;
    msg.msg = [MsgItem mj_objectWithKeyValues:originMsg.msg];
    
    if ([NSDate isExceed30DayWithTagetTimestamp:msg.msg.createtime] == YES) {
        msg.msg.content = nil;
        if (msg.msg.filePath == nil) {
            [MBProgressHUD showTipMessageInView:@"当前文件已过期，不可转发" timer:1.0f];
            return;
        }
    }
    
    AddressListVC *friendListVC = [AddressListVC new];
    @weakify(self);
    [friendListVC setDidSelectFriendItemBlock:^(FriendItem * _Nonnull item) {
        @strongify(self);
//        [self sendCarMsgWithFriendInfo:item];
        SendCardAlert *alert = [SendCardAlert new];
//        FriendItem *friend = (FriendItem *)msg.content;
        [alert showWithContent:msg.msg.lastMsgTip toUserName:item.displayName toUserAvatar:item.avatar];
        @weakify(alert);
        [[alert.sendBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(alert);
            [alert hide];
            if (self.frowardingMsgBlock) {
                self.frowardingMsgBlock(msg, item);
            }
            [self dismissViewControllerAnimated:YES completion:^{
                [MBProgressHUD showTipMessageInWindow:@"转发成功" timer:1.0f];
            }];
        }];
    }];
    
    friendListVC.listType = 1;
    UINavigationController *nv = [[BaseNavigationController alloc] initWithRootViewController:friendListVC];
    [self presentViewController:nv animated:YES completion:nil];
}
- (void)didClickDeleteMenuItem {
    
    MsgModel *msg = [self.dataSource objectAtIndex:self.longPressIndexPath.row];
    MsgModel *lastMsg = [self.dataSource objectAtIndex:self.longPressIndexPath.row - 1];
    NSIndexPath *lastIndexPath = nil;
    if (lastMsg.msg.type == MsgType_Time && (self.longPressIndexPath.row + 1 <= self.dataSource.count)) {
        MsgModel *nextMsg = nil;
        if (self.longPressIndexPath.row + 1 < self.dataSource.count) {
            nextMsg = [self.dataSource objectAtIndex:self.longPressIndexPath.row + 1];
        }
        if (nextMsg == nil || nextMsg.msg.type == MsgType_Time) {
            [MsgItem deleteWithWhere:@{@"message_id": @[@(msg.msg.message_id), @(lastMsg.msg.message_id)]}];
            lastIndexPath = [NSIndexPath indexPathForRow:self.longPressIndexPath.row-1 inSection:0];
            [self.dataSource removeObject:lastMsg];
        } else {
            [MsgItem deleteWithWhere:@{@"message_id": @(msg.msg.message_id)}];
        }
    } else {
        [MsgItem deleteWithWhere:@{@"message_id": @(msg.msg.message_id)}];
    }
    [self.dataSource removeObject:msg];
    
    [self.tableView deleteRowsAtIndexPaths:lastIndexPath?@[lastIndexPath, self.longPressIndexPath]:@[self.longPressIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (void)didClickRecallMsg {
    MsgModel *msg = [self.dataSource objectAtIndex:self.longPressIndexPath.row];
    [MBProgressHUD showActivityMessageInView:@"正在撤回消息..."];
    @weakify(self);
    [[YBApiManager.shareManager recallMsgWithMsgId:msg.msg.remote_msg_id?:msg.msg.message_id] subscribeNext:^(id  _Nullable x) {
        [MBProgressHUD hideHUD];
//        NSDictionary *dataDic = [x objectForKey:@"data"];
//        msg.msg.content = @"你撤回了一条消息";
        msg.msg.content = @"撤回消息";
        msg.msg.type = MsgType_Tip;
        [msg.msg updateToDB];
        @strongify(self);
        if (msg == self.dataSource.lastObject) {
            [[NSNotificationCenter defaultCenter] postNotificationName:notification_NewSession_created object:self.session];
        }

        [self.tableView reloadRowsAtIndexPaths:@[self.longPressIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}
- (void)didClickLinkWithUrlStr:(NSString *)urlStr {
    AXWebViewController *webVC = [[AXWebViewController alloc] initWithURL:urlStr.h5ToURL];
    [self.navigationController pushViewController:webVC animated:YES];
}

#pragma mark - UIMenuController处理
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    //    if (!self.isFirstResponder) { // 文本框弹出键盘, 文本框才是第一响应者
    //        if (action == @selector(ding:)
    //            || action == @selector(reply:)
    //            || action == @selector(warn:)) return NO;
    //        //如果是文本框,那么这些显示都不返回
    //    }
    if (action == @selector(didClicForwardingMenuItem) ||
        action == @selector(didClickDeleteMenuItem) ||
        action == @selector(didClickRecallMsg)) {
        return YES;
    }
    
    return [super canPerformAction:action withSender:sender];
}

#pragma mark - other actions
- (void)didClickReportUser {
    EVCPopInputView *popView = [EVCPopInputView popInputViewWithTitle:@"举报用户" subTitle:nil placehold:@"请输入举报内容" preset:nil];
    [popView show];
    [popView clickButtonAction:^(NSInteger index, NSString *content) {
        if (index == 1) {
            [kUsermanager getFriendWithUserId:@"" groupId:self.session.group_id callbackBlock:^(FriendItem * _Nonnull friendItem) {
                [self reportUser:friendItem.friend_id content:content];
            }];
        }
    }];
}
- (void)reportUser:(NSString *)userid content:(NSString *)content {
    [MBProgressHUD showActivityMessageInView:@""];
    [[YBApiManager.shareManager reportUserWithUserid:userid content:content] subscribeNext:^(id  _Nullable x) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showTipMessageInWindow:@"举报成功" timer:1.0f];
        
    } error:^(NSError * _Nullable error) {
        [MBProgressHUD hideHUD];
        if ([error isServerError]) {
            [MBProgressHUD showTipMessageInView:error.localizedDescription timer:1.0f];
        } else {
            [MBProgressHUD showTipMessageInView:@"网络错误，请重试" timer:1.0f];
        }
    }];
}
- (void)didClickRightBarBtnItemAction {
    
    
    [LBXAlertAction showAlertWithTitle:@"提示" msg:@"确定删除聊天记录吗？" buttonsStatement:@[@"取消", @"确定"] chooseBlock:^(NSInteger buttonIdx) {
        if (buttonIdx) {
            if (self.session) {
                BOOL isDel = [MsgItem deleteWithWhere:@{@"group_id": self.session.group_id}];
                if (isDel == NO) {
                    isDel = [MsgItem deleteWithWhere:@{@"group_id": self.session.group_id}];
                }
                if (isDel == NO) {
                    [MBProgressHUD showTipMessageInView:@"删除聊天记录失败,请重试" timer:1.0f];
                } else {
                    [self.dataSource removeAllObjects];
                    [self.tableView reloadData];
                    self.session.last_msg_id = 0;
                    self.session.last_msg_time = @"";
                    [self.session updateToDB];
                    [[NSNotificationCenter defaultCenter] postNotificationName:notification_NewSession_created object:self.session];
                }
            }
        }
    }];
}

- (void)scrollToBottom {
    if (self.dataSource.count > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataSource.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}

- (void)updateTableView_Frame {
    NSLog(@"self tableView frame = %@", NSStringFromCGRect( self.tableView.frame));
    if (self.lastTableViewHeight <= 0) {
        [self scrollToBottom];
        self.lastTableViewHeight = self.tableView.height;
        return;
    }
    CGFloat newH = self.tableView.height;
    
    if (newH < self.lastTableViewHeight) {
        CGPoint offset = self.tableView.contentOffset;
        offset.y += self.lastTableViewHeight - newH;
        [UIView animateWithDuration:0.15 animations:^{
            self.tableView.contentOffset = offset;
        }];
    }
    self.lastTableViewHeight = self.tableView.height;
}


@end
